import React, { Component } from 'react';
import dealerLevel from './DealerLevel.module.css';
import { Row, Col, Button, Modal, Input, message, Tooltip, Select } from 'antd';
import { DeleteOutlined, FormOutlined, ToTopOutlined, ExclamationCircleOutlined, EllipsisOutlined } from '@ant-design/icons';
import axios from 'axios';
import http from '../../util/http'
import * as url from '../../util/api';
const { Option } = Select;
export default class DealerLevel extends Component {
    constructor(props) {
        super(props)
        this.state = {
            // list:
                // [{ client_level_id: 1, client_level_name: '普通', client_discount: '100%', default: true },
                // { client_level_id: 2, client_level_name: '一级代理', client_discount: '60%' },
                // { client_level_id: 3, client_level_name: '二级代理', client_discount: '70%' },
                // { client_level_id: 4, client_level_name: '三级代理', client_discount: '80%' },
                // { client_level_id: 5, client_level_name: '四级代理', client_discount: '90%' },
                // { client_level_id: 6, client_level_name: '五级代理', client_discount: '100%' },
                // ]
        }
    }
    toPoint(percent) {
        let reg = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/)
        if(reg.test(percent)){
            let str = percent.replace("%", "");
            str = str / 100;
            return str;
        }else{
            return percent
        }
        
    }
    toPercent(point) {
        let reg = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/)
        if(reg.test(point)){
            return point
        }else{
            let str = Number(point * 100).toFixed(1);
            str += "%";
            return str;
        }  
    }
    getDealer() {
        // axios({
        //     url: '/api' + url.queryClientLevel,
        //     method: 'post',
        // }).then(res => {
        //     console.log(res, '获取级别返回结果')
        // })
        http({
            url:url.queryClientLevel,
            method: 'post',
            data:{},
        }).then(res=>{
            console.log(res.data.data,'获取返回')
            this.setState({
                list:res.data.data
            })
        })
    }
    componentDidMount() {
        this.getDealer()
    }
    showNewDealerModule = () => {
        this.setState({
            isShowNewDealer: true
        })
    }
    handelNewChange = (e) => {
        let val = e.target.value.replace(/\s+/g, "")//获取属性值
        let name = e.target.name//获取表单元素的name属性
        console.log(666, val, name)
        this.setState({
            [name]: val
        })
    }
    confirmNew = () => {
        let reg = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/)
        if (this.state.level === undefined || this.state.level === '') {
            message.error('请输入级别名称！！！')
        } else if (this.state.discount === undefined || this.state.discount === '') {
            message.error('请输入订货折扣！！！')
        } else if (!reg.test(this.state.discount)) {
            message.error('请输入正确订货折扣！！')
        }
        else {
            // 向服务器发起请求判断级别名字是否重复
            axios({
                url: '/api' + url.judgeClientLevelName,
                method: 'post',
                data: { clientLevelName: this.state.level }
            }).then(res => {
                console.log(res, '判断名字返回值')
                if (res.data.code === 200) {
                    // 向服务器发起请求存储经销商
                    let obj = {
                        clientLevelName: this.state.level,
                        clientDiscount: this.toPoint(this.state.discount),
                    }
                    axios({
                        url: '/api' + url.addClientLevel,
                        method: 'post',
                        data: obj
                    }).then(res => {
                        console.log(res, '新增返回结果')
                        if (res.data.code === 200) {
                            message.success('新增成功!')
                            this.getDealer()
                            this.setState({
                                isShowNewDealer: false,
                                level: '',
                                discount: '',
                            })
                        } else {
                            message.error('新增失败！')
                        }
                    })
                } else {
                    message.error('经销商级别名字重复！！')
                }
            })
        }

    }
    handleNewCancel = () => {
        this.setState({
            isShowNewDealer: false
        })
    }
    // 置顶
    toTop = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.list))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].clientLevelId === id) {
                let obj = arr[i];
                arr.splice(i, 1);
                arr.unshift(obj);
            }
        }
        this.setState({
            list: arr
        }, () => {
            message.info('操作成功！！')
        })

    }
    // 修改
    editDealer = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.list))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].clientLevelId === id) {
                this.setState({
                    editDiscount: this.toPercent(arr[i].clientDiscount),
                    editLevel: arr[i].clientLevelName,
                    editId: arr[i].clientLevelId,
                })
            }
        }
        this.setState({
            isShowEditDealer: true,
        })


    }
    handelEditChange = (e) => {
        let val = e.target.value.replace(/\s+/g, "")//获取属性值
        let name = e.target.name//获取表单元素的name属性
        this.setState({
            [name]: val
        })
    }
    confirmEdit = () => {
        let reg = new RegExp(/^(100|[1-9]?\d(\.\d\d?\d?)?)%$|0$/)
        if (this.state.editLevel === undefined || this.state.editLevel === '') {
            message.error('请输入级别名称！！！')
        } else if (this.state.editDiscount === undefined || this.state.editDiscount === '') {
            message.error('请输入订货折扣！！！')
        } else if (!reg.test(this.state.editDiscount)) {
            message.error('请输入正确订货折扣！！')
        }
        else {
            axios({
                url: '/api' + url.judgeClientLevelName,
                method: 'post',
                data: { clientLevelName: this.state.editLevel }
            }).then(res => {
                console.log(res, '判断名字返回值')
                if (res.data.code === 200) {
                     // 向服务器发起请求存储修改的经销商
                    let obj = {
                        clientDiscount: this.toPoint(this.state.editDiscount),
                        clientLevelId: this.state.editId,
                        clientLevelName: this.state.editLevel
                    }
                    axios({
                        url: '/api' + url.updateClientLevel,
                        method: 'post',
                        data: obj
                    }).then(res => {
                        console.log(res, '修改返回结果')
                        if (res.data.code === 200) {
                            message.success('修改成功！')
                            this.getDealer()
                            this.setState({
                                isShowEditDealer: false,
                                editLevel: '',
                                editDiscount: '',
                            })
                            
                        } else {
                            message.error('修改失败')
                        }
                    })
                } else {
                    message.error('经销商级别名字重复！！')
                }
            })
           
            
        }

    }
    handleEditCancel = () => {
        this.setState({
            isShowEditDealer: false

        })
    }
    // 删除
    deleteDealer = (id) => {
        let arr = JSON.parse(JSON.stringify(this.state.list))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].clientLevelId === id) {
                console.log(arr[i].clientLevelName, 6666)
                this.setState({
                    nowLevel: arr[i].clientLevelName,
                    nowId: arr[i].clientLevelId,
                })
            }
        }
        // 向服务器发起请求 判断客户是否有此级别
        axios({
            url:'/api' + url.judgeClientLevelHasClient,
            method:'post',
            data:{clientLevelId:this.state.nowId}
        }).then(res=>{
            console.log(res,'判断客户返回结果')
            if(res.data.code === 200){
                axios({
                    url:'/api' + url.delClientLevel,
                    method:'post',
                    data:{clientLevelId:this.state.nowId}
                }).then(res=>{
                    console.log(res,'删除返回结果')
                    if(res.data.code === 200){
                        message.success('删除成功！')
                        this.getDealer()
                    }else{
                        message.error('删除失败！')
                    }
                })
            }else{
                this.setState({
                    isShowDeleteDealer: true,
                })
            }
        })
       
    }
    handleSelectChange = (value) => {
        let arr = JSON.parse(JSON.stringify(this.state.list))
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].clientLevelId === value) {
                this.setState({
                    deleteNeedData: {
                        original: this.state.nowId,
                        target: arr[i].clientLevelId,
                    }

                })
            }
        }
    }
    confirmDelete = () => {
        console.log(this.state.deleteNeedData, 6565)
        if (this.state.deleteNeedData === undefined) {
            message.error('请选择客户移至的级别！！')
        } else {
            // 向服务器发起请求
            let obj = {
                clientLevelId:this.state.original,
                newClientLevelId:this.state.target
            }
            axios({
                url:'/api' + url.delClientLevel,
                method:'post',
                data:obj
            }).then(res=>{
                console.log(res,'删除返回结果')
                if(res.data.code === 200){
                    message.success('删除成功！')
                    this.getDealer()
                    this.setState({
                        isShowDeleteDealer: false
                    })
                }else{
                    message.error('删除失败！')
                }
            })
            
        }

    }
    handleDeleteCancel = () => {
        this.setState({
            isShowDeleteDealer: false
        })
    }
    render() {
        return (
            <div className={dealerLevel.content}>
                <Row className={dealerLevel.btnBox}>
                    <Col span={24}>
                        <Button type="primary" className={dealerLevel.newBtn}
                            onClick={this.showNewDealerModule}>新增</Button>
                        <Modal
                            title="新增经销商级别"
                            visible={this.state.isShowNewDealer}
                            onOk={this.confirmNew}
                            cancelText={'取消'}
                            okText={'确定'}
                            onCancel={this.handleNewCancel}
                        >
                            <div className={dealerLevel.inputBox}>
                                <span className={dealerLevel.newTips}> <span>*</span>级别名称</span>
                                <Input className={dealerLevel.newDealer} name='level'
                                    value={this.state.level} onChange={this.handelNewChange} />
                            </div>
                            <div className={dealerLevel.inputBox}>
                                <span className={dealerLevel.newTips}> <span>*</span>订货折扣</span>
                                <Input className={dealerLevel.newDealer} name='discount'
                                    value={this.state.discount} onChange={this.handelNewChange} />
                            </div>
                        </Modal>
                    </Col>
                </Row>
                <Row className={dealerLevel.rowTitle}>
                    <Col span={10} className={dealerLevel.title}>级别名称</Col>
                    <Col span={10} className={dealerLevel.title}>订货折扣</Col>
                    <Col span={4} className={dealerLevel.title}></Col>
                </Row>
                {this.state.list?this.state.list.map(item =>
                    <Row className={dealerLevel.row} key={item.clientLevelId}>
                        <Col span={10} className={dealerLevel.name}>{item.clientLevelName}</Col>
                        <Col span={10} className={dealerLevel.discount}>{this.toPercent(item.clientDiscount)}</Col>
                        <Col span={4} >
                            <div className={dealerLevel.operate}>
                                {/* <div className = {dealerLevel.operateBtn}>
                            <button><FormOutlined className = {dealerLevel.operateIcon} />修改</button>
                            <button onClick = {()=>{this.toTop(item.client_level_id)}}><ToTopOutlined className = {dealerLevel.operateIcon} />置顶</button>
                            {item.default?null:<button onClick = {()=>{this.deleteDealer(item.id)}} ><DeleteOutlined className = {dealerLevel.operateIcon}  />删除</button>}
                            
                        </div> */}
                                <Tooltip title={() => {
                                    return <div className={dealerLevel.operateBtn}>
                                        <button onClick={() => { this.editDealer(item.clientLevelId) }} >
                                            <FormOutlined className={dealerLevel.operateIcon} />修改
                                        </button>
                                        <button onClick={() => { this.toTop(item.clientLevelId) }}>
                                            <ToTopOutlined className={dealerLevel.operateIcon} />置顶
                                        </button>
                                        {item.default ? null :
                                            <button onClick={() => { this.deleteDealer(item.clientLevelId) }} >
                                                <DeleteOutlined className={dealerLevel.operateIcon} />删除
                                            </button>

                                        }
                                    </div>
                                }} placement="bottom">
                                    <EllipsisOutlined className={dealerLevel.dot} />
                                </Tooltip>
                                <Modal
                                    maskStyle={{ backgroundColor: 'rgba(0,0,0,.15)' }}
                                    title="修改经销商级别"
                                    visible={this.state.isShowEditDealer}
                                    onOk={this.confirmEdit}
                                    cancelText={'取消'}
                                    okText={'确定'}
                                    onCancel={this.handleEditCancel}
                                >
                                    <div className={dealerLevel.inputBox}>
                                        <span className={dealerLevel.newTips}> <span>*</span>级别名称</span>
                                        <Input className={dealerLevel.newDealer} name='editLevel'
                                            value={this.state.editLevel} onChange={this.handelEditChange} />
                                    </div>
                                    <div className={dealerLevel.inputBox}>
                                        <span className={dealerLevel.newTips}> <span>*</span>订货折扣</span>
                                        <Input className={dealerLevel.newDealer} name='editDiscount'
                                            value={this.state.editDiscount} onChange={this.handelEditChange} />
                                    </div>
                                </Modal>
                                <Modal
                                    maskStyle={{ backgroundColor: 'rgba(0,0,0,.15)' }}
                                    title={'删除' + '"' + (this.state.nowLevel ? this.state.nowLevel : '') + '"' + '客户级别'}
                                    visible={this.state.isShowDeleteDealer}
                                    onOk={this.confirmDelete}
                                    cancelText={'取消'}
                                    okText={'确定'}
                                    onCancel={this.handleDeleteCancel}
                                >
                                    <p className={dealerLevel.deleteDescribe}><ExclamationCircleOutlined className={dealerLevel.describeIcon} />删除该客户级别需将此级别下的客户转移到以下级别</p>
                                    <div className={dealerLevel.inputBox}>
                                        <span className={dealerLevel.newTips}> <span>*</span>客户移至</span>
                                        {/* <Input className={dealerLevel.newDealer} name='editLevel'
                                            value={this.state.editLevel} onChange={this.handelEditChange} /> */}
                                        <Select defaultValue="请选择" className={dealerLevel.levelSelect} onChange={this.handleSelectChange}>
                                            {this.state.list.map(item => <Option key={item.clientLevelId} value={item.clientLevelId} disabled={this.state.nowId == item.clientLevelId ? true : false}>{item.clientLevelName}</Option>)}
                                        </Select>
                                    </div>
                                </Modal>
                            </div>
                        </Col>
                    </Row>):null}
            </div>
        )
    }
}
